<?php
/**
 * Search Help : Missions
 * To select a mission when looking at a contact
 * 
 * 
 */
/* @var $contact Hive\Ressource */
use Fox\Behaviors;
use Hive\Mission;
use Doctrine\DBAL\Connection;
use Fox\Dao\SqlFragment;
$contact = Xview::instance()->component('ressource', 'object');
$rid = $contact->getId();
$searchHelp = new Fox\Html\SearchHelp('hive-missions');
$searchHelp->setMultiple(new Fox\Html\Button('select',
						"ReloadFromSelectLines('#b_GRhive-missions','missionsContent','?mod=ressource&act=missions&rid=$rid');"))
				->closeOnClick(true);
$searchHelp->width('500');
$searchHelp->block()
		->item('mission_description')
		->useLike()
		->size(20)
		->id('description');
$searchHelp
		->block()
		->item('mission_reference')
		->useLike()
		->size(20)->id('reference');
// Groups
$finder = new Hive\Ressource\Group();
$searchHelp
		->block()
		->item('mission_group')
		->options($finder->find(),'grouping','name');
$searchHelp
		->block()
		->item('mission_group')
		->id('grouping');		
if(!Fox\Authorization\Manager::check(Hive\Ressource::AUTH_GROUP_CAN_CHG)) {
	$searchHelp
		->block()->item('mission_group')->input(false);
}
$searchHelp->switchToObjectMode();
$searchHelp->grid()->fieldcat()->field('missionid')->SetHiddenInput(true)->hidden();
$searchHelp->grid()->fieldcat()->field('mission_reference')->width(100);
if(isset($_POST['dbcnt']))
{
	$inputs = $searchHelp->screen()->get();
	$fragments[] = $searchHelp->screen()->fragments();
	foreach($contact->missions() as $mission)
	{
		$excludedMissions[] = $mission->getId();
	}
	if(isset($excludedMissions))
		$fragments[] = new SqlFragment('missionid NOT IN (?)',array($excludedMissions),array(Connection::PARAM_INT_ARRAY));

	$finder = new Mission();
	$fragments[] = new SqlFragment('status NOT IN (?) OR status IS NULL',array(array(Mission::STATUS_CLOSED)),
			array(Connection::PARAM_STR_ARRAY));
	$res = $finder->find(Fox\Dao\SqlFragment::combine($fragments),array('title' => false),null,$_POST['dbcnt']);
	
	$searchHelp->grid()->fieldcat()->setGenerators(array(
		'mission_reference' => Fox\Generator::useAttribute('reference'),
		'mission_description' => Fox\Generator::useFunction(function($data) {
			return mb_substr($data->description,0,40,_CHARSET_).'...';
			
		})
	));
	
	echo $searchHelp->displayGrid($res);
}
else
{
	echo $searchHelp->display();
}